package dryven.view.engine.parser.componentinvocation;

import dryven.reflection.TypeRef;
import dryven.view.ViewDataDictionary;
import dryven.view.engine.expression.ExpressionCompilationException;
import dryven.view.engine.expression.CompiledViewExpression;
import dryven.view.engine.expression.ViewExpression;
import dryven.view.engine.parser.CompilationException;
import dryven.view.engine.parser.ViewDataDeclarationCollection;

public class ExpressionAttributeBinding implements
		AttributeBinding {

	private String _expression;
	private CompiledViewExpression _compiledExpression;
	
	public ExpressionAttributeBinding(String expression) {
		super();
		_expression = expression;
	}

	@Override
	public Class<?> getBoundType() {
		return _compiledExpression.getExpressionType().getTypeClass();
	}

	@Override
	public Object getValue(ViewDataDictionary viewData) {
		return _compiledExpression.evaluate(viewData);
	}

	@Override
	public void compile(ViewDataDeclarationCollection declarations) throws CompilationException {
		ViewExpression expr = new ViewExpression(_expression, declarations.getViewDataDeclarations());
		_compiledExpression = expr.compile();
	}

	@Override
	public Class<?> getBoundGenericType(int index) {
		int i = 0;
		for (TypeRef t : _compiledExpression.getExpressionType().getGenericTypeParams()) {
			if(i==index) {
				return t.getTypeClass();
			}
		}
		return null;
	}

	@Override
	public boolean isLiteral() {
		return false;
	}

}
